const {
  createEducationalExperience, //  添加教学经历
  updateEducationalExperience, //  更新教学经历
  requestSubscribeMessage,
} = require('../../../../api/index');
const {
  getBatchDict
} = require('../../../../utils/dict');
const WXBizDataCrypt = require('../../../../utils/WXBizDataCrypt');

const {
  validate,
} = require('../../../../utils/util');

const {
  education_access
} = require('../../../../utils/config');

// pages/authentication/index/index.js
Page({
  data: {
    selectSchool: 'addExperience2',
    isSelectImage: false,
    type: '',
    index: 0,
    educationDicts: [],
    genderDicts: [],
    yearDicts: [],
    cityDicts: [],
    formData: {
      id: '',
      locations: [], //  缓存 省市
      schoolName: "",
      department: "",
      major: "",
      education: "",
      locationProvince: "",
      locationCity: "",
      enrollmentYear: "",
      educationPhoto: ''
    },
    errors: {},
    rules: {
      schoolName: [{
        empty: true,
        msg: '学校名不能为空'
      }],
      department: [{
        empty: true,
        msg: '院系不能为空'
      }],
      major: [{
        empty: true,
        msg: '专业不能为空'
      }],
      education: [{
        empty: true,
        msg: '学历不能为空'
      }],
      locations: [{
        empty: true,
        msg: '所在省市不能为空'
      }],
      enrollmentYear: [{
        empty: true,
        msg: '入学时间不能为空'
      }],
      educationPhoto: [{
        empty: true,
        msg: '材料截图不能为空'
      }]
    }
  },
  //  页面跳转
  onJump(event) {
    const {
      url
    } = event.currentTarget.dataset;
    wx.navigateTo({
      url
    });
  },
  //  修改表单数据
  onFormData(event) {
    const {
      prop
    } = event.currentTarget.dataset;
    this.data.formData[prop] = event.detail;
  },
  // 提交数据
  async onSubmit(event) {
    const error = validate(this.data.formData, this.data.rules);

    if (error) { //  如果报错就不允许进行数据的提交
      this.setData({
        errors: error
      });
      return;
    }

    fetchFormData.call(this);
  },
  onShow() {
    const _data = this.data.formData;
    const collegeName = wx.getStorageSync(this.data.selectSchool)?.collegeName;
    collegeName && (_data.schoolName = collegeName);
    _data.educationName = this.data.educationDicts.find(_s => _s.code === _data.education)?.name;
    if (_data.locations.length > 0) {
      _data.locationName = _data.locations[0] + '/' + _data.locations[1];
    } else {
      _data.locationName = '';
    }

    this.setData({
      formData: JSON.parse(JSON.stringify(_data))
    });
  },
  onUnload() {
    wx.removeStorageSync(this.data.selectSchool);
  },
  onSelectImage() { //  选择图片
    this.data.isSelectImage = true;
  },
  /*** 生命周期函数--监听页面加载 */
  async onLoad(options) {
    wx.showLoading({
      title: '加载中...'
    });
    //  设置年份下拉框的数据
    const yearSelect = this.selectComponent('#define-select');
    yearSelect.setActions(getYearDicts());
    //  处理字典项
    await fetchDict.call(this);

    //  设置城市  用于测试
    const citySelect = this.selectComponent('#city-select');
    citySelect.setActions(this.data.cityDicts);

    const {
      id,
      index
    } = options;
    this.data.index = index;
    this.data.formData.id = id;

    //  处理初始化数据
    await getResult.call(this, index);

    wx.hideLoading();
  }
})

//  提交表单数据
async function fetchFormData() {
  const func = this.data.formData.id ? updateEducationalExperience : createEducationalExperience;
  const type = this.data.formData.id ? 'edit_education' : 'add_education';

  const _data = setResult(JSON.parse(JSON.stringify(this.data.formData)));
  const {
    errors
  } = await func(_data);
  if (errors.length > 0) {
    return;
  }

  const arr = wx.getStorageSync('educationalExperienceList');

  if (type === 'edit_education') {
    arr[this.data.index] = this.data.formData;
    wx.setStorageSync('educationalExperienceList', arr);
  } else {
    //  将成功的记录保存起来，便于后期使用
    arr.push(this.data.formData);
    wx.setStorageSync('educationalExperienceList', arr);
  }

  //  授权成功 之后调整页面
  const res = await requestSubscribeMessage([education_access]);

  if (res[education_access] = "accept") {
    wx.showToast({
      title: '订阅成功',
      icon: 'success',
      duration: 1000,
      success() {
        //  填写完成之后 返回到上一页
        wx.navigateTo({
          url: `/packageA/pages/success/index?type=${ type }`
        });
      }
    })
  } else { //  提示未通过
    //  填写完成之后 返回到上一页
    wx.navigateTo({
      url: `/packageA/pages/success/index?type=${ type }`
    });
  }
}

//  获取并设置字典项
async function fetchDict() {
  const [educationDicts = [], genderDicts = [], cityDicts = []] = await getBatchDict(
    ['EDUCATION', 'GENDER', {
      pageNumber: 1,
      pageSize: 50,
      dictName: "XZQH",
      codeLike: "%0000"
    }]);

  this.data.educationDicts = educationDicts;
  this.data.genderDicts = genderDicts;
  this.data.cityDicts = cityDicts.map(item => {
    item.text = item.name;
    item.value = item.code;
    return item;
  });
}

//  处理回显数据
function getResult(index) {
  if (!this.data.formData.id) return;
  const res = wx.getStorageSync('educationalExperienceList')[index];
  res.locations = [res.locationProvince, res.locationCity];
  res.locationName = res.locationProvince + '/' + res.locationCity;
  res.educationName = this.data.educationDicts.find(_s => _s.code === res.education)?.name;

  this.setData({
    formData: res
  });
  return res;
}

//  处理表单数据
function setResult(data) {
  const _data = JSON.parse(JSON.stringify(data));
  _data.locationProvince = _data.locations[0];
  _data.locationCity = _data.locations[1];

  return _data;
}

// 获取年份列表 从 当前年份开始向下，去 150年
function getYearDicts() {
  const dicts = [];
  const curYear = new Date().getFullYear();
  for (let i = curYear; i >= curYear - 150; i--) {
    const d = String(i);
    dicts.push({
      name: d + '年',
      code: d
    })
  }

  return dicts;
}